/**
 * 优先队列
 */
function PriorityQueue() {
  function QueueElement(ele, priority) {
    this.ele = ele;
    this.priority = priority;
  }
  let insert = function(obj) {
    let { priority } = obj;
    if (this.isEmpty()) {
      this.item.push(obj);
      return;
    }
    let flag = true;
    //右到左
    // for (let i = this.item.length; i > 0; i--) {
    //   let pre = this.item[i - 2];
    //   let current = this.item[i - 1];
    //   if ((priority < current.priority && pre && priority > pre.priority) ||(priority < current.priority && !pre)) {
    //     this.item.splice(i - 1, 0, obj);
    //     flag = false;
    //     break;
    //   }
    // }
    // 左到右
    for (let i = 0; i < this.item.length; i++) {
      if (priority < this.item[i].priority) {
        this.item.splice(i, 0, obj);
        flag = false;
        break;
      }
    }
    if (flag) this.item.push(obj);
  };

  this.item = [];

  let p = PriorityQueue.prototype;
  p.enqueue = function(ele, priority) {
    let qe = new QueueElement(ele, priority);
    insert(qe);
  };
  p.isEmpty = function() {
    if (this.item.length == 0) return true;
    else return false;
  };

  p.dequeue = function() {
    return this.item.shift();
  };
  p.front = function() {
    return this.item[0];
  };
  p.toString = function() {
    return this.item;
  };
  p.size = function() {
    return this.item.length;
  };
}

let pq = new PriorityQueue();
pq.enqueue(1, 10);
pq.enqueue(0, 2);
pq.enqueue(1.5, 5);
console.log(pq.toString());
pq.enqueue(30, 1);
console.log(pq.toString());
pq.enqueue(30, 0);
console.log(pq.toString());
pq.enqueue(30, 2.335);
console.log(pq.toString());
pq.enqueue(30, 100);
console.log(pq.toString());
